<template>
  <div class="page-modal">
    <el-dialog
      v-model="dialogVisible"
      :title="isEditFormData"
      width="30%"
      center
    >
      <MyForm
        v-bind="modalConfig"
        v-model="formData"
        @update:modelValue="updateModalChange"
      />
      <slot></slot>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfim"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { computed, ref, watch } from "vue";
import MyForm from "@/base-ui/form";
import useSystemStore from "@/store/system.js";
export default {
  components: { MyForm },
  props: {
    modalConfig: {
      type: Object,
      required: true,
    },
    defaultInfo: {
      type: Object,
      default: () => ({}),
    },
    pageName: {
      type: String,
      default: "",
    },
  },
  setup(props) {
    const dialogVisible = ref(false);
    const formData = ref({});

    // 判断dialog标题
    const isEditFormData = computed(() => {
      if (Object.keys(props.defaultInfo).length) {
        return "eidt " + props.pageName;
      } else {
        return "create " + props.pageName;
      }
    });

    // 点击编辑添加编辑信息
    watch(
      () => props.defaultInfo,
      (newValue) => {
        for (const item of props.modalConfig.formItems) {
          formData.value[`${item.field}`] = newValue[`${item.field}`];
        }
      }
    );

    // 编辑删除操作
    const store = useSystemStore();
    const handleConfim = () => {
      if (Object.keys(props.defaultInfo).length) {
        store.editPageData({
          pageName: props.pageName,
          editData: { ...formData.value },
          id: props.defaultInfo.id,
        });
      } else {
        // 新增
        store.createPageData({
          pageName: props.pageName,
          newData: { ...formData.value, ...props.otherInfo },
        });
      }
      dialogVisible.value = false;
    };

    const updateModalChange = (e) => {
      // console.log(e);
    };

    return {
      dialogVisible,
      formData,
      handleConfim,
      isEditFormData,
      updateModalChange,
    };
  },
};
</script>

<style lang="less" scoped></style>
